package cumeo89.chii.client.ui;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Text;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

public class SeperatedPanel extends TrivialPanel implements ExtendedPanel {

	private String separatingString;

	public SeperatedPanel() {
		this(", ");
	}

	public SeperatedPanel(String separatingString) {
		this("span", separatingString);
	}

	public SeperatedPanel(String tag, String separatingString) {
		super(tag);
		if (separatingString == null) {
			throw new NullPointerException();
		}
		this.separatingString = separatingString;
	}

	public void add(Widget child) {
		super.add(child);
		validate();
	}

	public void insert(Widget newChild, int index) {
		super.insert(newChild, index);
		validate();
	}

	@Override
	public boolean remove(Widget w) {
		boolean result = super.remove(w);
		validate();
		return result;
	}

	private void validate() {
		boolean seperated = true;
		Element element = getElement();
		NodeList<Node> children = element.getChildNodes();
		for (int i = children.getLength() - 1; i >= 0; i--) {
			Node child = children.getItem(i);
			if (child.getNodeType() == Node.TEXT_NODE
					&& separatingString.equals(child.getNodeValue())) {
				if (seperated || i <= 0) {
					element.removeChild(child);
				}
				seperated = true;
			} else {
				if (!seperated) {
					Text text = Document.get().createTextNode(separatingString);
					element.insertBefore(text, child.getNextSibling());
				}
				seperated = false;
			}
		}
	}

}
